﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using wenku8.Entity;
using wenku8.Parser;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace wenku8.Xamls
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class NovelContentPage : Page
    {
        private ObservableCollection<Illustration> Illustrations { get; set; }
        private HtmlDocument htmlDoc;

        public NovelContentPage()
        {
            this.InitializeComponent();
            htmlDoc = new HtmlDocument();
            Illustrations = new ObservableCollection<Illustration>();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var novelContentUri = e.Parameter as string;
            var htmlPage = await HTMLParser.GetHtmlString(novelContentUri);
            if (htmlPage == null) {
                MainPage.PopMessageDialog("网络或服务器故障！");
                return;
            }

            htmlDoc.LoadHtml(htmlPage);
            var title = htmlDoc.GetElementbyId("title").InnerText;
            if (title.Contains("插图")) {
                Illustrations.Clear();
                illustrationsListView.Visibility = Visibility.Visible;
                novelContentScrollViewer.Visibility = Visibility.Collapsed;
                IllustrationUriParser.GetIllustrationsAsync(htmlPage, Illustrations);
            }
            else {
                illustrationsListView.Visibility = Visibility.Collapsed;
                novelContentScrollViewer.Visibility = Visibility.Visible;
                novelContentTextBlock.Text = NovelTextParser.GetNovelText(htmlPage);
                novelContentScrollViewer.ChangeView(null, 0, null);
            }
            MainPage.DisableProgressRing();
        }

        // 
        protected override void OnKeyDown(KeyRoutedEventArgs e)
        {
            novelContentScrollViewer.ChangeView(null, novelContentScrollViewer.VerticalOffset + 2, null);
            base.OnKeyDown(e);
        }

        private void OnUpKeyDown(object sender, KeyRoutedEventArgs e)
        {
            novelContentScrollViewer.ChangeView(null, novelContentScrollViewer.VerticalOffset + 2, null);
        }

    }
}
